﻿using System;
using System.Collections.Generic;
using System.ServiceModel;
using Hopscotch.Common.Logging;
using Hopscotch.Common.Services.Wcf;
using Hopscotch.Server.AppServiceFake;
using Microsoft.Practices.Unity;

namespace Hopscotch.Application.FakeServer
{
    public class WcfServiceManager : IDisposable
	{
		static readonly ILogger logger = AppLogger.CreateLogger<WcfServiceManager>();
		private readonly List<ServiceHost> serviceHosts = new List<ServiceHost>();
		private readonly IUnityContainer container;

		public WcfServiceManager(IUnityContainer container)
		{
			this.container = container;
		}

		public void Start()
		{
			//App Services:
			OpenHost<AuthenticationService>();
			OpenHost<InstrumentService>();
			OpenHost<CurrencyInstrumentService>();
			OpenHost<TradeService>();
		}

		public void CloseAll()
		{
			foreach (ServiceHost serviceHost in serviceHosts)
			{
				serviceHost.Close();
			}
		}

		private void OpenHost<T>()
		{
			Type type = typeof(T);
			//ServiceHost serviceHost = new ServiceHost(type);
			UnityServiceHost serviceHost = new UnityServiceHost(type);
			serviceHost.Container = container;

			logger.Info("Open host: {0}", type.Name);
			serviceHost.Open();
			serviceHosts.Add(serviceHost);
		}

		public void Dispose()
		{
			//TODO: Implement!!
			//throw new NotImplementedException();
		}
	}
}
